<template>
    <div class="app-container">
        <public-search @on-query="handleQuery" @on-reset="resetQuery">
            <el-form :model="queryParams" ref="queryForm" size="small" inline>

                <el-form-item label="主单元" prop="id1">
                    <el-select size="small" style="width: 100%;" v-model="queryParams.id1" placeholder="请选择主单元" clearable
                        @change="handleFirstChange">
                        <el-option v-for="(item, index) in firstList" :key="index" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分单元" prop="id2">
                    <el-select size="small" style="width: 100%;" v-model="queryParams.id2" placeholder="请选择分单元" clearable
                        @change="handleSecondChange">
                        <el-option v-for="(item, index) in secondList" :key="index" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="作业活动步骤" prop="id3">
                    <el-select size="small" style="width: 100%;" v-model="queryParams.id3" placeholder="请选择作业活动步骤" clearable
                        @change="handleQuery">
                        <el-option v-for="(item, index) in thirdList" :key="index" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="风险等级" prop="evaluateRiskLevel">
                    <el-select size="small" v-model="queryParams.evaluateRiskLevel" placeholder="请选择风险等级" clearable
                        style="width: 100%;" @change="handleQuery">
                        <el-option v-for="dict in dict.type.risk_level" :key="dict.value" :label="dict.label"
                            :value="dict.label" />
                    </el-select>
                </el-form-item>

            </el-form>
        </public-search>

        <public-table>
            <template slot="operate">
                <div style="display: flex;justify-content: flex-end;">
                    <el-upload :action="uploadFileUrl" accept=".xls,.xlsx" :limit="1" :on-error="handleUploadError"
                        :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers">
                        <el-button type="primary">导入</el-button>
                    </el-upload>

                    <el-button type="primary" @click="handleAdd" style="margin-left: 10px;">新增</el-button>
                </div>
            </template>
            <template slot="table">
                <div>
                    <el-tabs v-model="queryParams.tabName" @tab-click="handleChangeTab">
                        <el-tab-pane label="作业活动风险管控清单模板" name="1"></el-tab-pane>
                        <el-tab-pane label="跟班干部检查模板" name="2"></el-tab-pane>
                    </el-tabs>
                    <el-table v-loading="loading" border :data="dataList" :span-method="arraySpanMethod" max-height="800">
                        <el-table-column label="序号" align="center" width="50px" type="index" />
                        <el-table-column label="主单元" prop="firstLevelName" width="150" />
                        <el-table-column label="分单元" prop="secondLevelName" width="120" />
                        <el-table-column label="作业活动步骤" prop="thirdLevelName" width="180" />
                        <el-table-column label="风险因素" prop="riskFactor" min-width="150" />
                        <el-table-column label="可能导致事故类型" prop="accidentType" width="200" />
                        <el-table-column label="主要管控措施" prop="controlMeasure" min-width="100" />
                        <el-table-column label="风险等级" prop="evaluateRiskLevel" width="130" align="center" />
                        <el-table-column label="推送到" prop="pushTo" width="170" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110"
                            fixed="right">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
                                <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </template>

            <template slot="pagination">
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" layout="prev, pager, next, jumper" />
            </template>
        </public-table>



        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>


            <el-form inline size="small">
                <el-form-item label="主单元">
                    <el-input v-model="form.mainName"></el-input>
                </el-form-item>
                <div class="child-content">
                    <div class="child-item" v-for="(second, index) in form.points" :key="index">
                        <div class="main-cell">
                            <el-form-item label="分单元" style="width: 100%;">
                                <el-input v-model="second.pointName" style="width: 100%;"></el-input>
                            </el-form-item>
                            <div class="buttons">
                                <el-button v-if="form.points.length > 0" type="danger" plain size="mini"
                                    @click="() => form.points.splice(index, 1)">移除</el-button>
                                <el-button v-if="index === form.points.length - 1" type="primary" plain size="mini"
                                    @click="onAddSecondChild">添加</el-button>
                            </div>
                        </div>
                        <div class="child-content">
                            <div class="child-item" v-for="(third, i) in second.activities" :key="index + '-' + i">
                                <div class="main-cell">
                                    <el-form-item label="作业活动步骤" style="width: 100%;">
                                        <el-input v-model="third.activityName" style="width: 100%;"></el-input>
                                    </el-form-item>
                                    <div class="buttons">
                                        <el-button v-if="second.activities.length > 0" type="danger" plain size="mini"
                                            @click="() => second.activities.splice(i, 1)">移除</el-button>
                                        <el-button v-if="i === second.activities.length - 1" type="primary" plain
                                            size="mini" @click="onAddThirdChild(second.activities)">添加</el-button>
                                    </div>
                                </div>
                                <div>
                                    <el-form-item label="风险因素">
                                        <el-input v-model="third.riskFactor"></el-input>
                                    </el-form-item>
                                    <el-form-item label="可能导致事故类型">
                                        <el-input v-model="third.accidentType"></el-input>
                                    </el-form-item>
                                    <el-form-item label="主要管控措施">
                                        <el-input v-model="third.controlMeasure"></el-input>
                                    </el-form-item>
                                    <el-form-item label="风险等级">
                                        <el-select size="small" v-model="third.evaluateRiskLevel" placeholder="请选择风险等级"
                                            style="width: 200px;">
                                            <el-option v-for="dict in dict.type.risk_level" :key="dict.value"
                                                :label="dict.label" :value="dict.label" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="推送到">
                                        <el-input v-model="third.pushTo"></el-input>
                                    </el-form-item>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </el-form>



            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="cancel" size="small">取 消</el-button>
                <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
            </div>
        </el-dialog>


    </div>
</template>
  
<script>
import { getToken } from "@/utils/auth";
import Api from '@/api/business/risk-libs/index'
import { mapGetters } from 'vuex'
import { cloneDeep } from "lodash"
const options = {
    page: {
        title: "风险库管理",
        name: "RiskLibs"
    },
    row: {
        id: "thirdLevelId",
        title: ""
    },
    form: {
        insertTitle: "新增风险库项目",
        updateTitle: "编辑风险库项目",
    }
}

const defaultThirdData = {
    "activityName": "", //活动名称
    "riskFactor": "", //风险因素
    "accidentType": "", //可能导致事故类型
    "controlMeasure": "", //主要管控措施
    "evaluateRiskLevel": "",
    "pushTo": "" //推送到
}
const defaultSecondData = {
    pointName: "",
    activities: [cloneDeep(defaultThirdData)]
}
const getDefaultFormData = (tabName) => {
    return cloneDeep({
        "tabName": tabName,
        "mainName": "", //主单元名称
        points: [cloneDeep(defaultSecondData)]
    })
}
export default {
    name: options.page.name,
    dicts: ['risk_level'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            dataList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,

            // 日期范围
            dateRange: [],

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 1,
                tabName: "1",
                id1: "",
                id2: "",
                id3: "",
                evaluateRiskLevel: "",
            },
            form: {},
            firstList: [],
            secondList: [],
            thirdList: [],
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/riskList/importRiskList", // 上传文件服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
        }
    },
    computed: {
        ...mapGetters(["user"])
    },
    created() {
        this.getList()
        this.queryFirstList()
    },
    methods: {
        handleUploadError(err) {
            this.$modal.msgError("导入失败，请重试");
        },
        // 上传成功回调
        handleUploadSuccess(res, file) {
            if (res.code === 200) {
                this.resetQuery()
            } else {
                this.$modal.msgError(res.msg);
            }
        },
        handleChangeTab() {
            this.queryParams.pageNum = 1
            this.queryParams.id1 = ""
            this.queryParams.id2 = ""
            this.queryParams.id3 = ""
            this.queryParams.evaluateRiskLevel = ""
            this.$nextTick(() => {
                this.getList()
                this.queryFirstList()
            })
        },

        handleFirstChange() {
            this.queryParams.id2 = ""
            this.queryParams.id3 = ""
            this.thirdList = []
            this.querySecondList(this.queryParams.id1)
            this.handleQuery()
        },

        handleSecondChange() {
            this.queryParams.id3 = ""
            this.queryThirdList(this.queryParams.id2)
            this.handleQuery()
        },


        queryFirstList() {
            Api.queryChildDataByParentId(this.queryParams.tabName, 0).then(list => {
                this.firstList = list
            })
        },

        querySecondList(parentId) {
            Api.queryChildDataByParentId(this.queryParams.tabName, parentId).then(list => {
                this.secondList = list
            })
        },

        queryThirdList(parentId) {
            Api.queryChildDataByParentId(this.queryParams.tabName, parentId).then(list => {
                this.thirdList = list
            })
        },

        /** 查询数据列表 */
        getList() {
            this.loading = true
            Api.query(this.addDateRange(this.queryParams, this.dateRange)).then(res => {

                this.total = res.total
                this.loading = false
                const resList = res.data || []


                const dataList = []


                const firstLevelData = resList.filter(item => item.parentId === 0 && ![97, 98].includes(item.id))

                firstLevelData.forEach(fData => {
                    const secondLevelData = resList.filter(item => item.parentId === fData.id)
                    const firstChildList = []
                    if (secondLevelData.length) {
                        secondLevelData.forEach(sData => {
                            const thirdLevelData = resList.filter(item => item.parentId === sData.id)
                            const secondChildList = []
                            if (thirdLevelData.length) {
                                thirdLevelData.forEach(tData => {
                                    const item = {
                                        accidentType: tData.accidentType,
                                        controlMeasure: tData.controlMeasure,
                                        evaluateRiskLevel: tData.evaluateRiskLevel,
                                        pushTo: tData.pushTo,
                                        riskFactor: tData.riskFactor,
                                        firstLevelId: fData.id,
                                        firstLevelName: fData.name,
                                        secondLevelId: sData.id,
                                        secondLevelName: sData.name,
                                        thirdLevelId: tData.id,
                                        thirdLevelName: tData.name,
                                        firstSpan: { rowspan: 0, colspan: 0 },
                                        secondSpan: { rowspan: 0, colspan: 0 },
                                    }
                                    secondChildList.push(item)
                                })
                            } else {
                                secondChildList.push({
                                    accidentType: "",
                                    controlMeasure: "",
                                    evaluateRiskLevel: "",
                                    pushTo: "",
                                    riskFactor: "",
                                    firstLevelId: fData.id,
                                    firstLevelName: fData.name,
                                    secondLevelId: sData.id,
                                    secondLevelName: sData.name,
                                    thirdLevelId: "",
                                    thirdLevelName: "",
                                    firstSpan: { rowspan: 0, colspan: 0 },
                                    secondSpan: { rowspan: 0, colspan: 0 },
                                })
                            }

                            secondChildList[0].secondSpan = { rowspan: secondChildList.length, colspan: 1 }
                            firstChildList.push(...secondChildList)

                        })
                    } else {
                        firstChildList.push({
                            accidentType: "",
                            controlMeasure: "",
                            evaluateRiskLevel: "",
                            pushTo: "",
                            riskFactor: "",
                            firstLevelId: fData.id,
                            firstLevelName: fData.name,
                            secondLevelId: "",
                            secondLevelName: "",
                            thirdLevelId: "",
                            thirdLevelName: "",
                            firstSpan: { rowspan: 0, colspan: 0 },
                            secondSpan: { rowspan: 1, colspan: 1 },
                        })
                    }


                    firstChildList[0].firstSpan = { rowspan: firstChildList.length, colspan: 1 }
                    dataList.push(...firstChildList)
                })

                this.dataList = dataList

            }
            )
        },


        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 1) {
                return row.firstSpan
            }
            if (columnIndex === 2) {
                return row.secondSpan
            }
        },

        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },

        // 表单重置
        reset() {
            this.form = getDefaultFormData(this.queryParams.tabName)
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.secondList = []
            this.thirdList = []
            this.resetForm('queryForm')
            this.handleQuery()
        },


        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = options.form.insertTitle
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const firstId = row.firstLevelId
            const firstName = row.firstLevelName
            const list = this.dataList.filter(item => item.firstLevelId === firstId)
            const secondList = [...new Set(list.map(item => item.secondLevelId))].map(id => list.find(item => item.secondLevelId === id))
            const form = {
                id: firstId,
                tabName: this.queryParams.tabName,
                mainName: firstName,
                points: secondList.map(item => {
                    return {
                        id: item.secondLevelId,
                        pointName: item.secondLevelName,
                        activities: list.filter(o => o.secondLevelId === item.secondLevelId).map(o => {
                            return {
                                id: o.thirdLevelId,
                                activityName: o.thirdLevelName,
                                riskFactor: o.riskFactor,
                                accidentType: o.accidentType,
                                controlMeasure: o.controlMeasure,
                                evaluateRiskLevel: o.evaluateRiskLevel,
                                pushTo: o.pushTo,
                            }
                        })
                    }
                })
            }
            this.form = cloneDeep(form)
            this.open = true
            this.title = options.form.updateTitle
        },





        onAddSecondChild() {
            this.form.points.push(cloneDeep(defaultSecondData))
        },
        onAddThirdChild(list) {
            list.push(cloneDeep(defaultThirdData))
        },


        /** 提交按钮 */
        submitForm: function () {
            if (this.form.mainName === '') return this.$modal.msgWarning('请输入主单元')

            try {
                this.form.points.forEach(item => {
                    if (item.pointName === '') throw "请输入分单元"
                    item.activities.forEach(val => {
                        if (val.activityName === '') throw "请输入作业活动步骤"
                        if (val.riskFactor === '') throw "请输入风险因素"
                        if (val.accidentType === '') throw "请输入可能导致事故类型"
                        if (val.controlMeasure === '') throw "请输入主要管控措施"
                        if (val.evaluateRiskLevel === '') throw "请选择风险等级"
                        if (val.pushTo === '') throw "请输入推送信息"
                    })
                })
            } catch (e) {
                return this.$modal.msgWarning(e)
            }


            if (this.form.id != undefined) {
                Api.update(this.form).then(response => {
                    this.$modal.msgSuccess('修改成功')
                    this.open = false
                    this.getList()
                })
            } else {
                Api.insert(this.form).then(response => {
                    this.$modal.msgSuccess('新增成功')
                    this.open = false
                    this.getList()
                })
            }
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row[options.row.id]
            this.$modal.confirm('删除不可恢复，是否确定删除？').then(function () {
                return Api.del(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            // this.download2(Api.export, { ...this.queryParams })
        }
    }
}
</script>
  
<style scoped lang="scss">
.child-content {
    padding-left: 30px;
    padding: 10px 10px 10px 30px;

    .child-item {
        margin: 15px 0;
        background: rgba(214, 230, 237, 0.3);
        border-radius: 6px;
        box-shadow: 0 0 4px rgba(203, 210, 213, 0.5);

        ::v-deep .el-form-item:last-child .el-form-item__label {
            width: 124px;
        }

        .main-cell {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .buttons {
                display: flex;
                align-items: center;
                padding-right: 20px;
            }
        }
    }

    .el-form-item {
        margin: 5px;
    }
}
</style>